﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NHunspell;
using System.Threading;

namespace OfficeClip.OpenSource.SpellO
{
	public partial class Form1 : Form
	{
		public Settings.SpellO spello;
		public Form1()
		{
			InitializeComponent();
		}

		private void btnAddNew_Click(object sender, EventArgs e)
		{
			AddNew an = new AddNew(this);
			an.ShowDialog();
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			this.Text = string.Format(
				"SpellO {0} - Spell Checker for Website (Beta)", 
				Constants.GetAppVersion().Substring(0,3)
				);
            this.toolTipSpello.SetToolTip(this.listResult, string.Empty);

			CheckForIllegalCrossThreadCalls = false;
			spello = Constants.Deserialize();
			cmbSiteId.Items.Add(string.Empty);
			PopulateCombo();
		}

		public void PopulateCombo()
		{
			cmbSiteId.Items.Clear();
			foreach (Settings.Site site in spello.Sites)
			{
				cmbSiteId.Items.Add(site.Id);
			}
		}

		private void btnDelete_Click(object sender, EventArgs e)
		{
			if (cmbSiteId.SelectedIndex == -1)
			{
				MessageBox.Show("No Site Id Selected",
						"Error",
						MessageBoxButtons.OK,
						MessageBoxIcon.Error,
						MessageBoxDefaultButton.Button1
				);
				return;
			}
			DialogResult result = MessageBox.Show("The Selected Site will be removed. Are you sure?",
					   "Deleting Site",
					   MessageBoxButtons.YesNo,
					   MessageBoxIcon.Warning,
					   MessageBoxDefaultButton.Button1
		   );
			if (result == DialogResult.No) return;
			for (int i = 0; i < spello.Sites.Count; i++)
			{
				if (spello.Sites[i].Id == (string)cmbSiteId.Items[cmbSiteId.SelectedIndex])
				{
					spello.Sites.RemoveAt(i);
					break;
				}
			}
			Constants.Serialize(spello);
			PopulateCombo();
		}

		public int GetCurrentIndex()
		{
			return cmbSiteId.SelectedIndex;
		}

		private void btnSettings_Click(object sender, EventArgs e)
		{
			if (cmbSiteId.SelectedIndex == -1)
			{
				MessageBox.Show("No Site Id Selected",
						"Error",
						MessageBoxButtons.OK,
						MessageBoxIcon.Error,
						MessageBoxDefaultButton.Button1
				);
				return;
			}
			SettingsForm an = new SettingsForm(this);
			an.ShowDialog();
		}

		//delegate void MyDelegate(string text, bool isUrl);

		private void RunWebCrawler()
		{
			btnAddNew.Enabled = false;
			btnDelete.Enabled = false;
			cmbSiteId.Enabled = false;
			btnSettings.Enabled = false;
			btnRun.Enabled = false;
			btnListAction.Visible = false;
			btnSuggestions.Visible = false;
			siteSettingsToolStripMenuItem.Enabled = false;
			this.runToolStripMenuItem.Enabled = false;
			listResult.Items.Clear();
			Program.log.WriteDebug("Starting New Run", "");
			for (int i = 0; i < spello.Sites.Count; i++)
			{
				if (spello.Sites[i].Id == (string)cmbSiteId.Items[cmbSiteId.SelectedIndex])
				{
					WebCrawler.Run(i, this);
					break;
				}
			}
			labProcessing.Visible = false;
			btnAddNew.Enabled = true;
			btnDelete.Enabled = true;
			cmbSiteId.Enabled = true;
			btnSettings.Enabled = true;
			btnRun.Enabled = true;
			siteSettingsToolStripMenuItem.Enabled = true;
			this.runToolStripMenuItem.Enabled = true;
        }

		private void btnRun_Click(object sender, EventArgs e)
		{
			if (cmbSiteId.SelectedIndex == -1)
			{
				MessageBox.Show("No Site Id Selected",
						"Error",
						MessageBoxButtons.OK,
						MessageBoxIcon.Error,
						MessageBoxDefaultButton.Button1
					);
				return;
			}
			labProcessing.Visible = true;
            this.toolTipSpello.SetToolTip(this.listResult, "Click (or double Click) on any word or web-site for more options");
            (new Thread(new ThreadStart(RunWebCrawler))).Start();
			//RunWebCrawler();
		}

		public void AddToList(string text, bool isUrl)
		{
			Application.DoEvents();
			listResult.Items.Add(text);
		}

		private void btnClose_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void siteSettingsToolStripMenuItem_Click(object sender, EventArgs e)
		{
			btnSettings_Click(sender, e);
		}

		private void runToolStripMenuItem_Click(object sender, EventArgs e)
		{
			btnRun_Click(sender, e);
		}

		private void exitToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void showLogToolStripMenuItem_Click(object sender, EventArgs e)
		{
			Constants.IEOpenOnURL(Program.log, Constants.GetSetupDir() + @"\log\index.html");
		}

		private void aboutSpellOToolStripMenuItem_Click(object sender, EventArgs e)
		{
            //(new About()).ShowDialog();
		}

		private void helpToolStripMenuItem1_Click(object sender, EventArgs e)
		{
            //MessageBox.Show("Not yet implemented",
            //    "Information",
            //    MessageBoxButtons.OK,
            //    MessageBoxIcon.Information,
            //    MessageBoxDefaultButton.Button1
            //);
		}

		private void ListAction(bool isButtonClick)
		{
			string item = ((string)listResult.Items[listResult.SelectedIndex]).Trim();
			if (string.IsNullOrEmpty(item)) return;
			if (item.StartsWith("http://") || item.StartsWith("https://"))
			{
				Constants.IEOpenOnURL(Program.log, item);
			}
			else
			{
				if (!isButtonClick)
				{
					DialogResult result = MessageBox.Show(
						string.Format("Add '{0}' to the Dictionary?", item),
							   "Add to Dictionary",
							   MessageBoxButtons.YesNo,
							   MessageBoxIcon.Question,
							   MessageBoxDefaultButton.Button1
				   );
					if (result == DialogResult.No)
					{
						return;
					}
				}
				else
				{
					MessageBox.Show(
						string.Format("Added '{0}' to the Dictionary", item),
							   "Added to Dictionary",
							   MessageBoxButtons.OK,
							   MessageBoxIcon.Information,
							   MessageBoxDefaultButton.Button1);
				}
				for (int i = 0; i < spello.Sites.Count; i++)
				{
					if (spello.Sites[i].Id == (string)cmbSiteId.Items[cmbSiteId.SelectedIndex])
					{
						List<string> words = spello.Sites[i].SpellCheck.AllowWords;
						if (!words.Contains(item))
						{
							words.Add(item);
							Constants.Serialize(spello);
						}
						break;
					}
				}
			}
			listResult.SelectedIndex = -1;
			btnListAction.Visible = false;
			btnSuggestions.Visible = false;
		}

		private void listResult_MouseDoubleClick(object sender, MouseEventArgs e)
		{
			ListAction(false);

		}

		private void listResult_MouseClick(object sender, MouseEventArgs e)
		{
			if (listResult.SelectedIndex == -1) return;
			btnListAction.Visible = true;
			string item = ((string)listResult.Items[listResult.SelectedIndex]).Trim();
			btnListAction.Visible = true;
			if (item.StartsWith("http://") || item.StartsWith("https://"))
			{
				btnListAction.Text = "Show Website";
				btnSuggestions.Visible = false;
			}
			else
			{
				btnListAction.Text = "Add to Dictionary";
				btnSuggestions.Visible = true;
			}
		}

		private void btnListAction_Click(object sender, EventArgs e)
		{
			ListAction(true);
		}

		private void btnSuggestions_Click(object sender, EventArgs e)
		{
			List<string> suggestions;
            string dictPrefix = Constants.GetSetupDir() + @"\";
			string item = ((string)listResult.Items[listResult.SelectedIndex]).Trim();
			using (Hunspell hunspell = new Hunspell(
                    dictPrefix + spello.Sites[cmbSiteId.SelectedIndex].SpellCheck.Dictionary + ".aff",
                    dictPrefix + spello.Sites[cmbSiteId.SelectedIndex].SpellCheck.Dictionary + ".dic"
             ))
				{
					suggestions = hunspell.Suggest(item);
				}
			StringBuilder sb = new StringBuilder();
			foreach (string lstr in suggestions)
			{
				sb.Append(lstr + System.Environment.NewLine);
			}
			MessageBox.Show(sb.ToString(),
					   "Suggestions",
					   MessageBoxButtons.OK,
					   MessageBoxIcon.Information,
					   MessageBoxDefaultButton.Button1);
		}

        private void helpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            (new About()).ShowDialog();
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            //Lets change the useable are on window resizing
            this.btnSettings.Left = this.Width - 133;

            this.listResult.Height =  this.Height - 140;
            this.listResult.Width   = this.Width - 34;

            this.btnSuggestions.Top = this.Height - 70;
            this.btnSuggestions.Left = this.Width - 369;
            this.btnListAction.Top = this.Height - 70;
            this.btnListAction.Left = this.Width - 256;
            this.btnRun.Top = this.Height - 70;
            this.btnRun.Left = this.Width - 142;
            this.btnClose.Top = this.Height - 70;
            this.btnClose.Left = this.Width - 81;
        }
	}
}
